package zhang.lao.service.console;/**
 * Created by zhangqin on 2017/9/1.
 */

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import zhang.lao.build.mybatis.jdbc.auto.model.SysSequence;
import zhang.lao.build.mybatis.jdbc.auto.model.SysSequenceExample;
import zhang.lao.build.tool.ListUtils;
import zhang.lao.dao.base.SysSequenceDao;

import java.util.List;

/**
 * @author
 * @create 2017-09-01 13:43
 **/
@Service
public class SysSequenceFactory {
    @Autowired
    private SysSequenceDao sysSequenceDao;

    @Transactional
    public synchronized int  getSequence(String key){
        SysSequenceExample sysSequenceExample = new SysSequenceExample();
        sysSequenceExample.createCriteria().andBelongBoEqualTo(key);
        if(sysSequenceDao.countByExample(sysSequenceExample)>0){
             SysSequence  sysSequence = ListUtils.getFirst(sysSequenceDao.selectByExample(sysSequenceExample));
            sysSequence.setNumber(sysSequence.getNumber()+1);
            sysSequenceDao.updateByPrimaryKeySelective(sysSequence);
            return sysSequence.getNumber();
        }else{
            SysSequence sysSequence = new SysSequence();
            sysSequence.setNumber(1);
            sysSequence.setBelongBo(key);
            sysSequenceDao.insert(sysSequence);
            return 1;
        }

    }
}
